# 实现代码的抽取
# from mall import settings

from rest_framework.views import APIView
from mall import settings
from urllib.parse import urlencode,parse_qs
from urllib.request import urlopen
from rest_framework.response import Response
from rest_framework import status
import json

"""
抽取代码的步骤：
1.分析出某一部分代码能实现特定的功能
2.将代码原封不动地复制到一个方法中，对应的数据如果没有，则以参数的形式传递
3.将复制的代码注释，用抽取的代码进行验证
"""""

class QQOauthTool(object):

    def get_oauth_url(self, request):

        #获取state
        # state = request.query_params.get('state')
        state = '/'
        #设置base_url,注意添加 ?
        base_url = 'https://graph.qq.com/oauth2.0/authorize?'
        #组织参数
        params = {
            'response_type':'code',
            'client_id':settings.QQ_APP_ID,
            'redirect_uri':settings.QQ_REDIRECT_URL,
            'state':state,
            'scope':'get_user_info',
        }

        #对参数进行urlencode,然后拼接url
        auth_url = base_url + urlencode(params)

        #返回响应
        return Response({'auth_url':auth_url})


    def get_token_by_code(self, request):

        code = request.query_params.get('code')

        if code is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # #注意添加 ?
        base_url = 'https://graph.qq.com/oauth2.0/token?'

        params = {
            'grant_type': 'authorization_code',
            'client_id': settings.QQ_APP_ID,
            'client_secret': settings.QQ_APP_KEY,
            'code': code,
            'redirect_uri': settings.QQ_REDIRECT_URL
        }

        url = base_url + urlencode(params)

        # 我们自己去请求来获取数据
        # 通过urlopen来请求url中数据
        response = urlopen(url)

        data = response.read().decode()
        # parse_qs将获取的参数转换为字典
        dict = parse_qs(data)

        access_token = dict.get('access_token')

        # if access_tokens:
        #     access_token = access_tokens[0]
        #
        # # 'access_token=C7299EDD52B07DC8B0B3DFF767909803&
        # # expires_in=7776000&
        # # refresh_token=CBCAC05971E8769268AC3DCFA5B72F6B'
        # # print(access_token)
        #
        # return access_token
        if access_token is None:
            raise Exception('获取token失败')

        return access_token[0]


    def get_openid_by_token(self, token):


        """
        PC网站：https://graph.qq.com/oauth2.0/me

        参数	是否必须	含义
        access_token	必须	在Step1中获取到的access token。

        """

        base_url = 'https://graph.qq.com/oauth2.0/me?'

        params = {
            'access_token':token
        }

        url = base_url + urlencode(params)

        # 自己获取数据,发送请求
        openid_response = urlopen(url)

        # 获取数据
        openid = openid_response.read().decode()

        # 对数据进行截取
        try:
            dict = json.loads(openid[10:-4])
        except Exception:
            raise Exception('获取数据失败')

        openid_real = dict.get('openid')

        return openid_real


